import 'package:flutter/material.dart';
import 'dart:io';

import 'package:flutter/services.dart';

enum ClearButtonMode {
  never,
  whileEditing,
  unlessEditing,
  always
}
enum InputBorderType{
  UnderlineType,
  OutlineType,
}
class CustomTextField extends StatefulWidget {
  final String hintText;
  Widget? leading;
  Widget? trailing;
  double leadingWidth; //如果有leading时，必须传宽度
  double trailingWidth; //如果有trailing时，必须传宽度
  double leadingMargin;
  double trailingMargin;
  InputBorderType inputBorderType;
  double borderRadius;
  double enabledBorderWidth;
  Color enabledBorderColor;
  double disabledBorderWidth;
  Color disabledBorderColor;
  double focusedBorderWidth;
  Color focusedBorderColor;

  final FocusNode? focusNode;
  final TextEditingController controller;
  final bool isInputPwd;
  final bool autoFocus;
  final TextInputType keyboardType;
  final TextInputAction textInputAction;
  final double height;
  final Color textColor;
  final double fontSize;
  final Color backgroundColor;
  final List<TextInputFormatter>? inputFormatters;
  final int maxLength;
  final ClearButtonMode clearButtonMode;
  // final bool readOnly;
  final bool enabled;
  CustomTextField({
    Key? key,
    required this.controller,
    this.hintText = '',
    this.leading,
    this.trailing,
    this.leadingWidth = 0,
    this.trailingWidth = 0,
    this.leadingMargin = 0,
    this.trailingMargin = 0,
    this.inputBorderType = InputBorderType.UnderlineType,
    this.borderRadius = 0,
    this.enabledBorderWidth = 0,
    this.enabledBorderColor = const Color(0xFFFFFFFF),
    this.disabledBorderWidth = 0,
    this.disabledBorderColor = const Color(0xFFFFFFFF),
    this.focusedBorderWidth = 0,
    this.focusedBorderColor = const Color(0xFFFFFFFF),
    this.focusNode,
    this.isInputPwd = false,
    this.autoFocus = false,
    this.keyboardType = TextInputType.text,
    this.textInputAction = TextInputAction.done,
    this.textColor = Colors.black,
    this.fontSize = 16,
    this.height = 44,
    this.backgroundColor = const Color.fromRGBO(255, 255, 255, 0),
    this.inputFormatters,
    this.maxLength = 100,
    this.clearButtonMode = ClearButtonMode.never,
    // this.readOnly = false,
    this.enabled = true,
  }) : super(key: key);

  @override
  State<CustomTextField> createState() => _CustomTextFieldState();
}

class _CustomTextFieldState extends State<CustomTextField> {

  bool _showClear = false;
  double _clearBtnWidth = 30;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _showClear = widget.clearButtonMode == ClearButtonMode.always ? true : false;
    widget.controller.addListener(isEmpty);

    widget.focusNode?.addListener(() {
      final bool isNotEmpty = widget.controller.text.isNotEmpty;
      setState(() {
        switch(widget.clearButtonMode){
          case ClearButtonMode.whileEditing:
            _showClear = widget.focusNode!.hasFocus ? (isNotEmpty ? true : false) : false;
            break;
          case ClearButtonMode.unlessEditing:
            _showClear = widget.focusNode!.hasFocus ? false : (isNotEmpty ? true : false);
        }
      });

    });
  }

  void isEmpty() {
    final bool isNotEmpty = widget.controller.text.isNotEmpty;
    setState(() {
      switch (widget.clearButtonMode) {
        case ClearButtonMode.whileEditing:
          _showClear = isNotEmpty ? true : false;
          break;
        case ClearButtonMode.unlessEditing:
          _showClear =
              widget.focusNode!.hasFocus ? false : (isNotEmpty ? true : false);
      }
    });
  }

  @override
  void dispose() {

    widget.controller.removeListener(isEmpty);
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {

    Widget textField = ConstrainedBox(constraints: BoxConstraints(
        maxHeight: widget.height,

      ),
        child: TextField(
        controller: widget.controller,
        focusNode: widget.focusNode,
        obscureText: widget.isInputPwd,
        autofocus: widget.autoFocus,
        keyboardType: widget.keyboardType,
        inputFormatters: widget.inputFormatters,
        maxLength: widget.maxLength,
        // readOnly: widget.readOnly,
        enabled: widget.enabled,
        decoration: InputDecoration(
          contentPadding: EdgeInsets.fromLTRB(
              widget.leadingWidth, 0, widget.trailingWidth + (_showClear ? _clearBtnWidth : 0), 0),
          hintText: widget.hintText,
          fillColor: widget.backgroundColor,
          filled: true,
          counterText:'',

          enabledBorder: (widget.inputBorderType == InputBorderType.UnderlineType) ?  UnderlineInputBorder(
            borderSide: BorderSide(
              color: widget.enabledBorderColor,
              width: widget.enabledBorderWidth,
            ),
          ) : OutlineInputBorder(
            borderSide: BorderSide(
              color: widget.enabledBorderColor,
              width: widget.enabledBorderWidth,
            ),
            borderRadius: BorderRadius.circular(widget.borderRadius),
          ),
            disabledBorder: (widget.inputBorderType == InputBorderType.UnderlineType) ?  UnderlineInputBorder(
              borderSide: BorderSide(
                color: widget.disabledBorderColor,
                width: widget.disabledBorderWidth,
              ),
            ) : OutlineInputBorder(
              borderSide: BorderSide(
                color: widget.disabledBorderColor,
                width: widget.disabledBorderWidth,
              ),
              borderRadius: BorderRadius.circular(widget.borderRadius),
            ),
          focusedBorder:  (widget.inputBorderType == InputBorderType.UnderlineType) ?  UnderlineInputBorder(
            borderSide: BorderSide(
              color: widget.enabledBorderColor,
              width: widget.enabledBorderWidth,
            ),
          ) : OutlineInputBorder(
            borderSide: BorderSide(
              color: widget.enabledBorderColor,
              width: widget.enabledBorderWidth,
            ),
            borderRadius: BorderRadius.circular(widget.borderRadius),
          ),
        ),
        style: TextStyle(
          color: widget.textColor,
          fontSize: widget.fontSize,
        ),
      ),
    );

    if (Platform.isAndroid) {
      textField = Listener(
        onPointerDown: (e) => FocusScope.of(context).requestFocus(widget.focusNode),
        child: textField,
      );
    }

    Widget? leadingWidget = widget.leading != null ? Positioned(
        left: widget.leadingMargin,
        child: widget.leading!
    ) : null;

    Widget? trailingWidget = widget.trailing != null ? Positioned(
        right: widget.trailingMargin,
        child: widget.trailing!
    ) : null;

    Widget? clearWidget = _showClear ? Positioned(
        right: widget.trailingWidth,
        child: GestureDetector(
          child: Image.asset(
            "images/clear_button.png",
            width: 25,
            height: 25,
          ),
          onTap: () => widget.controller.text = '',
        ),
    ) : null;
    return Stack(
      alignment: Alignment.centerLeft,
      children: [
        textField,
        if(leadingWidget != null) leadingWidget!,
        if(trailingWidget != null) trailingWidget!,
        if(clearWidget != null) clearWidget!,
      ],
    );

  }
}
